(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:ArticleCtrl
     * @description
     * # ArticleCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('ArticleCtrl', ArticleCtrl);

    ArticleCtrl.$inject = ['$scope', '$rootScope', 'dataService', '$timeout', '$location', 'helper', '$document', '$filter', '$sce', '$compile'];


    function ArticleCtrl($scope, $rootScope, dataService, $timeout, $location, helper, $document, $filter, $sce, $compile) {

        $scope.addCode = function($event) {
            // console.error("$event", $event.currentTarget.innerHTML);
            $rootScope.$broadcast("event:wx-ueditor-add-content", {
                content: $event.currentTarget.innerHTML,
                uid: $scope.wxuid,
            });
        }


        $scope.listAction = function() {
            $scope.tabtype = "news";
            $scope.$watch('wxappid', function(newValue, oldValue, scope) {
                if (newValue) {
                    $scope.wxappid = newValue;
                    $scope.getlist(1);
                }
            }, true);

        }


        $scope.addAction = function() {
            $scope.article = {};
            $scope.article.need_open_comment = true;
            $scope.article.only_fans_can_comment = 0;
            $scope.wxappid = $location.search().wxappid;
            $scope.media_id = $location.search().media_id;
            $scope.wxuid = $location.search().wxappid;
            if (!$scope.wxappid) {
                return helper.myAlert("没有选择公众号", "#/article/list");
            }
            if ($scope.media_id) {
                $scope.getOne();
            } else {
                $scope.articles = [{
                    title: "标题",
                    author: "",
                    content: "",
                    content_source_url: "",
                    need_open_comment: "",
                    show_cover_pic: "",
                    thumb_media_id: "",
                    thumb_url: "https://img.alicdn.com/imgextra/i3/20841398/TB2Si6IgRDH8KJjy1zeXXXjepXa-20841398.png",
                    url: "",
                }];
                // $scope.articles.push($scope.initdata);
                $scope.article = $scope.articles[0];
            }
            $scope.pageSize = 10;
            $scope.gzhscTagGet(1);
        }
        $scope.gzhscTagGet = function() {
            var query = {
                page_no: $scope.pageNo,
                page_size: $scope.pageSize,
            };
            dataService.gzhsutagGet(query).then(function(re1) {
                if (re1.gzhsc_tag_list) {
                    $scope.gzhsc_tag_list = re1.gzhsc_tag_list;
                    $scope.total_count = re1.total_count;
                }
            });

        }

        //点击查询 表情下的 素材
        $scope.getTaginfo = function(pageNo, tag_id) {
            $scope.pageNo = pageNo ? pageNo : "1";
            $scope.pageSize = $scope.pageSize ? $scope.pageSize : 10;
            var query = {
                content: {
                    page_no: $scope.pageNo,
                    page_size: $scope.pageSize,
                    gzhsc_tag_id: tag_id,
                    title: $scope.keyword,
                }
            };

            dataService.gzhscGet(query).then(function(re1) {
                console.error(re1);
                if (re1.gzhsc_list) {
                    $scope.gzhsc_list = re1.gzhsc_list;
                    $scope.total_count = re1.total_count;
                    console.error($scope.gzhsc_list);
                }
            });
        }

        $scope.addarticles = function() {
            $scope.articles.push({
                title: "标题",
                author: "",
                content: "",
                content_source_url: "",
                need_open_comment: "",
                show_cover_pic: "",
                thumb_media_id: "",
                thumb_url: "https://img.alicdn.com/imgextra/i3/20841398/TB2Si6IgRDH8KJjy1zeXXXjepXa-20841398.png",
                url: "",
            });
            console.error("$scope.articles", $scope.articles);
        }

        $scope.getLocalTime = function(nS) {
            return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
        }
        $scope.addimgurl = function(attach) {
            $timeout(function() {
                $scope.article.thumb_url = attach.url;
                $scope.article.thumb_media_id = attach.media_id;
            });
        }


        //删除素材
        $scope.delMedia = function(media_id) {
            helper.myConfirm('确定删除此条素材？', function() {
                $scope.postApi('wxDelMaterial', $scope.wxappid, { media_id: media_id }).then(function(t) {
                    if (t) {
                        helper.myAlert("删除素材成功");
                        $scope.getlist(1);
                    }
                });
            });
        }

        //保存 修改素材
        $scope.savedata = function(no) {

            if (!$scope.wxappid || $scope.articles.length < 0) {
                return;
            }
            if ($scope.wxappid && $scope.media_id) {
                $scope.address = {
                    "media_id": $scope.media_id,
                    "index": $scope.articles.length > 1 ? $scope.articles.length : 0,
                    "articles": []
                }
                var api = 'wxUpdateNews';
            }

            if (!$scope.media_id) {
                $scope.address = { articles: [] };
                var api = 'wxAddNews';
            }
            if ($scope.testData()) {
                post();
            }


            function post() {
                var i = 0;
                async.mapSeries($scope.articles, function(da, callback) {
                    var article = {
                        "title": da.title, //必须
                        "thumb_media_id": da.thumb_media_id,
                        "author": da.author,
                        "digest": da.digest,
                        "show_cover_pic": da.show_cover_pic,
                        "content": da.content,
                        "content_source_url": da.content_source_url,
                    }
                    if ($scope.media_id) {
                        $scope.address.articles = article;
                        $scope.address.index = i;
                        return $scope.postApi(api, $scope.wxappid, $scope.address).then(function(t) {
                            i = i + 1;
                            callback(null, t);
                        });
                    } else {
                        $scope.address.articles.push(article);
                        callback(null, 1);
                    }

                }, function(e, r) {
                    if ($scope.address && !$scope.media_id && r) {
                        $scope.postApi(api, $scope.wxappid, $scope.address).then(function(t) {
                            if (t) {
                                if (!no) {
                                    helper.myAlert("新增图文消息成功", "#/article/list");
                                } else {
                                    $scope.media_id = t;
                                    $scope.previewShow();
                                }
                            }
                        });
                    }
                    if ($scope.media_id && r) {
                        if (!no) {
                            helper.myAlert("修改图文消息成功");
                        } else {
                            $scope.previewShow();
                        }
                    }

                });
            }

        }
        //检验数据
        $scope.testData = function() {
            for (var i = $scope.articles.length - 1; i >= 0; i--) {
                if (!$scope.articles[i].content) return helper.myAlert("图文内容不能为空！");
                if (!$scope.articles[i].thumb_media_id) return helper.myAlert("图文封面不能为空！");
                if (!$scope.articles[i].title) return helper.myAlert("图文标题不能为空！");
                if (!$scope.articles[i].author) return helper.myAlert("图文作者不能为空！");
            }
            return true;
        }

        $scope.postApi = function(api, wxappid, address) {
            return dataService[api](wxappid, address).then(function(result) {
                return result;
            });
        }
        $scope.ChoiceTp = function(value) {
            $timeout(function() {
                $scope.article = value;
                $scope.description = $scope.article.content;
                $scope.AssembleContent();
                console.error("$scope.article", $scope.article);
            });

        }

        $scope.getOne = function() {
            console.error("$scope.wxappid",$scope.wxappid);
            if ($scope.wxappid) {
                $scope.address = {
                    "media_id": $scope.media_id,
                }
                dataService.wxproxy($scope.wxappid, 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=TOKEN', 'POST', $scope.address).then(function(result) {
                    if (result.news_item) {
                        $scope.articles = result.news_item;
                        $scope.ChoiceTp($scope.articles[0]);
                    } else {

                        helper.myAlert(result.Msg);
                    }
                });
            }

        }
        //组装数据 
        //$scope.description h是获取到的 content 内容
        $scope.AssembleContent = function() {
            //把转义 的网址加上 
            var str2 = $scope.description.replace(/="cn/g, '="https://mmbiz.qpic.cn');
            // console.error("dd", $scope.description);
            //根据 data-typef分割
            $scope.description = str2.split('data-src="');
            var sty = {};
            // console.error("$scope.description",$scope.description);
            _.map($scope.description, function(da, isk) {
                //从头开始进行截取 到" 号 
                var dd = da.substr(0, da.indexOf('"'));
                // var dd = da.substr(0, da.indexOf('data-src="'));
                // console.error("dd", dd);
                //判断 http 是否存在，存在的话，就说明是一个src 链接
                var d = dd.indexOf('http');
                //indexOf 如果存在的话，会返回0  
                if (d == 0) {
                    sty[isk] = dd;
                    // console.error("dd", dd);
                }
            });
            // console.error("sty",sty);
            var cont = '';
            //然后在进行把截取的字符串拼接在一起 
            _.map($scope.description, function(ddd, kkk) {
                if (kkk == 0) {
                    cont = ddd;
                } else {
                    //因为之前截取的时候是根据 k进行赋值的，k的值不变的，然后判断有没有值，
                    if (sty[kkk]) {
                        cont = cont + 'src ="' + sty[kkk] + '" data-src="' + ddd;
                    } else {
                        cont = cont + 'data-src="' + ddd;
                    }
                }
            });
            cont = cont.replace(/<a/g, '<a href=""');
            $scope.article.content = cont;
        }

        $scope.getlist = function(pageNo, offset) {
            if ($scope.wxappid) {

                console.error(pageNo);
                // var offset =pageNo>1?pageNo + 1:pageNo;
                $scope.address = {
                    "type": $scope.tabtype,
                    "offset": pageNo,
                    "count": $scope.pageSize ? $scope.pageSize : 10,
                }
                
                dataService.wxproxy($scope.wxappid, 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=TOKEN', 'POST', $scope.address).then(function(result) {
                    $scope.itemlist = result.item;
                    $scope.total_count = result.total_count;
                    $scope.item_count = result.item_count;
                });
            }

        }
        //群发
        $scope.sendall = function(media_id) {
            //
            var data = {
                "filter": {
                    "is_to_all": true, //所有用户
                },
                "mpnews": {
                    "media_id": media_id
                },
                "msgtype": "mpnews",
                "send_ignore_reprint": 0
            };

            helper.myConfirm('是否群发此图文消息！', function() {
                $scope.postApi('wxSendall', $scope.wxappid, data).then(function(t) {
                    if (t) {
                        helper.myAlert("群发成功");
                        // $scope.getlist();
                    }
                });
            });
        }
        //
        $scope.previewShow = function() {
            var qrcodeWin = $.alert({
                backdrop: "static",
                keyboard: false,
                title: '{{"预览"|translate}}',
                body: '<span>微信号:<input ng-model="towxname" type="text" name="name" class="input-xlarge"></span>',
                okBtn: '{{"预览"|translate}}',
                closeBtn: true,
                hasfoot: true,
                transition: true,
                width: 'small',
                show: function(e) {
                    $compile($(e.currentTarget).contents())($scope);
                },
                okHide: function(e) {
                    if ($scope.towxname) {
                        $scope.preview();
                    }
                },
                shown: function(e) {}
            });

        }

        //预览
        $scope.preview = function() {
            var data = {
                "towxname": $scope.towxname,
                "mpnews": {
                    "media_id": $scope.media_id
                },
                "msgtype": "mpnews"
            };

            $scope.postApi('preview', $scope.wxappid, data).then(function(t) {
                if (t) {
                    helper.myAlert("预览成功");
                    // $scope.getlist();
                }
            });
        }
    }
})();